package logrus

import (
	"fmt"
	"gitee.com/zhongguo168a/gocodes/myx/logx/iface"
	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	log "github.com/sirupsen/logrus"
	"os"
	"strings"
	"time"
)

func init() {

	//log.SetFormatter(new(Formatter))
	//log.SetReportCaller(false)
}

func NewLogger() (obj *Logger) {
	obj = &Logger{}
	l := log.New()
	obj.entity = l
	l.SetLevel(log.DebugLevel)

	l.SetFormatter(&log.JSONFormatter{
		TimestampFormat: "2006/01/02 15:04:05",
	})
	return
}

type Logger struct {
	Name   string
	entity log.FieldLogger
}

func (l *Logger) GetEntity() interface{} {
	return l.entity
}

func (l *Logger) UseFileRotation(path string) {

	/* 日志轮转相关函数
	`WithLinkName` 为最新的日志建立软连接
	`WithRotationTime` 设置日志分割的时间，隔多久分割一次
	WithMaxAge 和 WithRotationCount二者只能设置一个
	  `WithMaxAge` 设置文件清理前的最长保存时间
	  `WithRotationCount` 设置文件清理前最多保存的个数
	*/
	// 下面配置日志每隔 1 分钟轮转一个新文件，保留最近 3 分钟的日志文件，多余的自动清理掉。
	//writer, _ := rotatelogs.New(
	//	path+".%Y%m%d%H%M",
	//	rotatelogs.WithLinkName(path),
	//	rotatelogs.WithMaxAge(time.Duration(180)*time.Second),
	//	rotatelogs.WithRotationTime(time.Duration(60)*time.Second),
	//)

	writer, _ := rotatelogs.New(
		path+"_%Y%m%d%H%M.log",
		rotatelogs.WithLinkName(path),
		rotatelogs.WithRotationCount(7),
		rotatelogs.WithRotationTime(time.Duration(24)*time.Hour),
	)

	logger := l.entity.(*log.Logger)
	logger.SetOutput(writer)
	//log.SetFormatter(&log.JSONFormatter{})
}

func (l *Logger) Ok(a ...interface{}) {
	l.entity.Print("[ok   ] ")
	l.entity.Println(a...)
}

func (l *Logger) Fail(a ...interface{}) {
	l.entity.Print("[fail ] ")
	l.entity.Println(a...)
}

func (l *Logger) Msg(a ...interface{}) {
	l.entity.Println(a...)
}

func (l *Logger) Debug(a ...interface{}) {
	l.entity.Debugln(a...)
}

func (l *Logger) Warn(a ...interface{}) {
	l.entity.Warnln(a...)
}
func (l *Logger) Info(a ...interface{}) {
	l.entity.Println(a...)
}

func (l *Logger) Error(a ...interface{}) {
	l.entity.Errorln(a...)
}

func (l *Logger) Fatal(a ...interface{}) {
	l.entity.Fatalln(a...)
	os.Exit(-1)
}

func (l *Logger) With(m map[string]interface{}) iface.ILogger {
	n := &Logger{}
	n.entity = l.entity.WithFields(m)
	return n
}

type Formatter struct{}

func (s *Formatter) Format(entry *log.Entry) ([]byte, error) {
	timestamp := time.Now().Local().Format("2006/01/02 15:04:05")
	msg := fmt.Sprintf("%s [%s] %s\n", timestamp, strings.ToUpper(entry.Level.String()), entry.Message)
	return []byte(msg), nil
}
